package com.whut.whw.personalinfo;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.whut.whw.R;
import com.whut.whw.base.BaseActivity;
import com.whut.whw.model.User;
import com.whut.whw.util.GlideCircularLoadUtils;
import com.whut.whw.util.GsonUtils;
import com.whut.whw.util.LogUtils;
import com.whut.whw.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Call;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;
import static com.whut.whw.constant.ConfigConsts.BASE_URL;
import static com.whut.whw.util.GsonUtils.GsonString;


/**
 * Created by 曾旺红 on 2017/06/16.
 */

public class PsnDataActivity extends BaseActivity {

    public List<Object> list = new ArrayList<Object>();
    public static final int REQUEST_IMAGE = 100;


    @BindView(R.id.rv_psndata)
    RecyclerView recyclerView;

    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefreshLayout;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    PsnDataAdapter adapter;
    User user;

    private void initInfo() {
        String id= (String) getIntent().getSerializableExtra("ID");
        uploadPost(id);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_psn_data;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        initInfo();
        //指定布局方式
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        //适配器设置
        //PsnDataAdapter adapter=new PsnDataAdapter(list);
        adapter = new PsnDataAdapter(list);
        recyclerView.setAdapter(adapter);
        swipeRefreshLayout.setEnabled(false);
        //设置toolbar
        toolbar.setTitle("个人资料");
        toolbar.setTitleTextColor(ContextCompat.getColor(context, R.color.white));
        toolbar.setNavigationIcon(R.drawable.rc_back_icon);
    }

    @Override
    public void setListener() {
        LogUtils.d("dd", adapter == null);
        if (adapter != null) {
            adapter.setmOnItemClickListener(new PsnDataAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    switch (position) {
                        case 0:
                            PictureSelector.create(PsnDataActivity.this)
                                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                                    .imageSpanCount(3)// 每行显示个数 int
                                    .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                    .isCamera(true)// 是否显示拍照按钮 true or false
                                    .forResult(CHOOSE_REQUEST);//结果回调onActivityResult code
                            break;
                        case 1:
                            String name=((PsnDataModel) list.get(1)).getContent();
                            if(name.equals("设置昵称"))
                            {
                                name="";
                            }
                            showInputDialog("设置昵称", 1,20,name);
                            break;
                        case 2:
                            showDatePickDlg();
                            break;
                        case 3:
                            break;
                        case 4:
                            String sex = ((PsnDataModel) list.get(4)).getContent();
                            int index = sex == "女" ? 1 : 0;
                            showSingleChoiceDialog(index);
                            break;
                        case 5:
                            String email=((PsnDataModel) list.get(5)).getContent();
                            if(email.equals("设置邮箱"))
                            {
                                email="";
                            }
                            showInputDialog("设置邮箱", 5,30,email);
                            break;
                        case 6:
                            String tel=((PsnDataModel) list.get(6)).getContent();
                            if(tel.equals("设置手机号"))
                            {
                                tel="";
                            }
                            showInputDialog("设置手机号", 6,11,tel);
                            break;
                        case 7:
                            String intro=((PsnDataModel) list.get(7)).getContent();
                            if(intro.equals("设置个性签名"))
                            {
                                intro="";
                            }
                            showInputDialog("设置个性签名", 7,30,intro);
                            break;
                    }
                }
            });
        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                ImageView img = (ImageView) findViewById(R.id.data_photo);
                Glide
                        .with(PsnDataActivity.this)
                        .load(selectList.get(0).getPath())
                        .asBitmap().centerCrop()
                        .into(new GlideCircularLoadUtils(this, img));
            }
        }
    }

    int index;

    /**
     * 单选对话框
     */
    private void showSingleChoiceDialog(int pos) {
        final String[] items = {"男", "女"};


        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(PsnDataActivity.this);
        singleChoiceDialog.setTitle("性别");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, pos,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        index = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ((PsnDataModel) list.get(4)).setContent(items[index]);
                adapter.notifyDataSetChanged();
            }
        });
        singleChoiceDialog.show();
    }


    /**
     * 文本对话框
     * @param title 标题
     * @param index 点击的位置
     * @param lenth 文本框的最长输入
     * @param original 文本框初始值
     */
    private void showInputDialog(String title, final int index,int lenth,String original) {
    /*@setView 装入一个EditView
     */
        final EditText editText = new EditText(PsnDataActivity.this);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(lenth)}); //最大输入长度
        editText.setHint(lenth+"");
        if(!original.equals("")) {
            editText.setText(original);
        }
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(PsnDataActivity.this);
        inputDialog.setTitle(title).setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (index) {
                            case 1:
                                //编辑昵称
                                if(!editText.getText().toString().trim().equals("")) {
                                    ((PsnDataModel) list.get(1)).setContent(editText.getText().toString().trim());
                                    adapter.notifyDataSetChanged();
                                }
                                break;
                            case 5:
                                //编辑邮箱
                                if(!editText.getText().toString().trim().equals("")) {
                                    if(isEmail(editText.getText().toString().trim())) {
                                        ((PsnDataModel) list.get(5)).setContent(editText.getText().toString().trim());
                                        adapter.notifyDataSetChanged();
                                    }
                                    else
                                    {
                                        ToastUtils.showShort("请输入正确邮箱号！");
                                    }
                                }
                                break;
                            case 6:
                                //编辑手机号
                                if(!editText.getText().toString().trim().equals("")) {
                                    if(isMobile(editText.getText().toString().trim())) {
                                        ((PsnDataModel) list.get(6)).setContent(editText.getText().toString().trim());
                                        adapter.notifyDataSetChanged();
                                    }
                                    else
                                    {
                                        //getUiDelegate().toastLong("请输入有效手机号！");
                                        //SnackerbarUtils.Show_snakerbar("请输入有效手机号！");
                                        ToastUtils.showShort("请输入有效手机号！");
                                    }
                                }
                                break;
                            case 7:
                                //编辑个性签名
                                if(!editText.getText().toString().trim().equals("")) {
                                    ((PsnDataModel) list.get(7)).setContent(editText.getText().toString().trim());
                                    adapter.notifyDataSetChanged();
                                }
                                break;
                        }

                    }
                });
        inputDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    /**
     * 日期选择对话框
     */
    protected void showDatePickDlg() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(PsnDataActivity.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                //PsnDataActivity.this.mEditText.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
                ((PsnDataModel) list.get(2)).setContent(year + "-" + monthOfYear + "-" + dayOfMonth);
                adapter.notifyDataSetChanged();
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    @Override
    public void onBackPressed() {
        //传值到前一个页面
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("昵称", ((PsnDataModel) list.get(1)).getContent());
        bundle.putString("城市", ((PsnDataModel) list.get(3)).getContent());
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        //保存数据
        savePersonal();
        finish();
    }

    /**
     * 保存本页面的数据到数据库
     */
    public void savePersonal(){
        String nc=((PsnDataModel) list.get(1)).getContent().equals("设置昵称")?
                null:
                ((PsnDataModel) list.get(1)).getContent();
        Date csny=null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            csny=((PsnDataModel) list.get(2)).getContent().equals("设置生日")?
                    null:
                    sdf.parse(((PsnDataModel) list.get(2)).getContent());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String yhdz=((PsnDataModel) list.get(3)).getContent().equals("设置城市")?
                null:
                ((PsnDataModel) list.get(3)).getContent();
        char xb=((PsnDataModel) list.get(4)).getContent().equals("设置性别")?
                null:
                (((PsnDataModel) list.get(4)).getContent().equals("女")?'0':'1');
        String yx=((PsnDataModel) list.get(5)).getContent().equals("设置邮箱")?
                null:
                ((PsnDataModel) list.get(5)).getContent();
        String sjh=((PsnDataModel) list.get(6)).getContent().equals("设置手机号")?
                null:
                ((PsnDataModel) list.get(6)).getContent();
        String gxqm=((PsnDataModel) list.get(7)).getContent().equals("设置个性签名")?
                null:
                ((PsnDataModel) list.get(7)).getContent();

        user.setNc(nc);
        user.setCsny(csny);
        user.setYhdz(yhdz);
        user.setXb(xb);
        user.setYx(yx);
        user.setLxdh(sjh);
        user.setGxqm(gxqm);
        //ToastUtils.showLong(user.toString());

        final String TAG="PsnDataActivity:";
        Map<String, String> params = new HashMap<>();
        //String id=user.getYhbh();
        //params.put("User", user);
        String str=GsonUtils.GsonString(user);
        params.put("str",str);
//        Field[] userFd = user.getClass().getDeclaredFields(); //获取到user中的所有字段
//        for(Field f : userFd){
//            f.setAccessible(true);
//            Object obj=null;
//            try {
//                obj = f.get(user);
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            }
//            if(obj!=null){
//                if(f.getType()==Date.class){
//                    params.put(f.getName(),sdf.format((Date)obj));
//                    Log.e(TAG, "savePersonal: "+f.getName()+":"+sdf.format((Date)obj));
//                }
//                else{
//                    params.put(f.getName(),obj.toString());
//                    Log.e(TAG, "savePersonal: "+f.getName()+":"+obj.toString());
//                }
//            }
//        }

        String url = BASE_URL + "personal/modifydata";
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.d(TAG, "error");
                        ToastUtils.showLong("error: "+e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LogUtils.d(TAG, response);
                        //ToastUtils.showLong(response);
                        //jsonToString(response);
                    }
                });
    }
    /**
     * 照片转换成二进制
     *
     * @param bm
     * @return
     */
    private byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 验证手机号
     * @param number
     * @return
     */
    public static boolean isMobile(String number) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String num = "[1][358]\\d{9}";
        if (TextUtils.isEmpty(number)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return number.matches(num);
        }
    }

    /**
     * 验证邮箱
     * @param strEmail
     * @return
     */
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }
    /**
     * post
     */
    public void uploadPost(String id) {
        final String TAG="PsnDataActivity:";
        Map<String, String> params = new HashMap<>();
        params.put("id", id);

        String url = BASE_URL + "personal/maininfo";
        OkHttpUtils.post()//
                .url(url)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.d(TAG, "error");
                        ToastUtils.showLong("error: "+e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LogUtils.d(TAG, response);
                        //ToastUtils.showLong(response);
                        jsonToString(response);
                    }
                });
    }

    /**
     * 解析JSon字符串
     * @param json
     */
    public void jsonToString(String json){
        PersonalJSon pj = GsonUtils.GsonToBean(json,PersonalJSon.class);
        user=pj.getData().getUser();
        String yhtx=BASE_URL+"upload_img/tu2.jpg";
        String photopath="http://upload.jianshu.io/users/upload_avatars/3358298/167277b0-84f6-4b2c-a740-d117ab4687b6.jpg";
        //日期格式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //界面赋值
        list.add(yhtx);
        PsnDataModel data1 = new PsnDataModel("昵称", user.getNc());
        list.add(data1);
        PsnDataModel data2 = new PsnDataModel("生日", user.getCsny()==null?"设置生日":sdf.format(user.getCsny()));
        list.add(data2);
        PsnDataModel data3 = new PsnDataModel("地址", user.getYhdz()==null?"设置城市":user.getYhdz());
        list.add(data3);
        PsnDataModel data4 = new PsnDataModel("性别", user.getXb()=='1'?"男":(user.getXb()=='0'?"女":"设置性别"));
        list.add(data4);
        PsnDataModel data5 = new PsnDataModel("邮箱", user.getYx()==null?"设置邮箱":user.getYx());
        list.add(data5);
        PsnDataModel data6 = new PsnDataModel("手机号", user.getLxdh()==null?"设置手机号":user.getLxdh());
        list.add(data6);
        PsnDataModel data7 = new PsnDataModel("个性签名", user.getGxqm()==null?"设置个性签名":user.getGxqm());
        list.add(data7);
        adapter.notifyDataSetChanged();

    }
}
